package cn.sciento.boot.api.customize.generator;

import java.util.ArrayList;
import java.util.List;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import cn.sciento.boot.api.customize.commons.vo.ApiCustomizeRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CompositeCodeGenerator implements CodeGenerator {
  private static final Logger LOGGER = LoggerFactory.getLogger(CompositeCodeGenerator.class);
  
  private final List<AbstractCodeGenerator> codeGenerators;
  
  public CompositeCodeGenerator(List<AbstractCodeGenerator> codeGenerators) {
    this.codeGenerators = new ArrayList<>(codeGenerators);
  }
  
  public String generate(ClassPool classPool, CtClass targetClass, CtMethod targetMethod, ApiCustomizeRule rule, boolean returnValue) throws Exception {
    for (AbstractCodeGenerator codeGenerator : this.codeGenerators) {
      if (codeGenerator.support(rule.getTypeCode())) {
        return codeGenerator.generate(classPool, targetClass, targetMethod, rule, returnValue);
      }
    } 
    throw new IllegalArgumentException("error.unsupported.ruleType");
  }
  
  public void addCodeGenerator(AbstractCodeGenerator codeGenerator) {
    if (codeGenerator == null) {
      throw new IllegalArgumentException("Code generator is null");
    }
    this.codeGenerators.add(codeGenerator);
  }
}
